import React, { useState, memo, useRef, useEffect } from 'react';
import { Layout, Typography } from 'antd';
import { SvgIcon } from '@/components/icon';
import { useRouter } from '@/router/hooks';
import {
  useConfig,
  useDatasetFlag,
  useApiFlag,
  useAppInfo,
  useInitializeData,
  useConfigActions,
} from '@/store/configStore';
import HeaderLogo from '@/pages/components/logo';
import useWindowWidth from '@/hooks/event/use-window-width';
import usePermission from '@/hooks/event/usePermission';
import HomeMenuList from '@/pages/components/menus/HomeMenuList';
import { useRoleManage } from '@/store/roleManageStore';

import './styles/management.css';
import AppManagerIcon from '@/assets/icons/ic_app_manager.svg';
import { BrandingEnum } from '@/common';

import JoyrideGuide from '@/pages/components/joyride-guide';
import { useTranslation } from 'react-i18next';
import { useUserInfo } from '@/store/userStore';

const { Sider, Content } = Layout;
const { Text } = Typography;

const App: React.FC = () => {
  const { t } = useTranslation();
  const initializeData = useInitializeData();

  const { username } = useUserInfo();

  const router = useRouter();
  const { id } = useConfig();
  const datasetFlag = useDatasetFlag();
  const apiFlag = useApiFlag();
  const { isPc } = useWindowWidth();
  const [logoShow, setLogoShow] = useState(false);
  const { isAdmin } = usePermission();
  const { isEnableRoleConditions } = useRoleManage();
  const appInfoInitialize = useAppInfo();

  const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
  const licenseFlag = LICENSEFLAG === 'true' ? true : false;

  const openOrFocusTab = (tabUrl: string, tabName: string) => {
    const tabWindow = window.open('', tabName);
    if (tabWindow && !tabWindow.closed && tabWindow.location.href === tabUrl) {
      tabWindow.focus();
    } else {
      window.open(tabUrl, tabName);
    }
  };

  const { fetchInitialInfo } = useConfigActions();
  useEffect(() => {
    const init = async () => {
      fetchInitialInfo();
    };
    if (!id) {
      init();
    }
  }, []);

  const roleMenus = [
    {
      key: t('page.management.roles'),
      title: t('page.management.roles'),
      iconBackground: 'rgb(51, 173, 255, 0.2)',
      icon: (
        <SvgIcon
          icon="icon-park-solid--people-two"
          size={40}
          style={{
            borderRadius: '12px',
            padding: '3px',
            color: '#33ADFF',
          }}
        />
      ),
      onClick: () => {
        router.push(`/role/manage`);
      },
      desc: t('page.management.rolesDesc'),
    },
  ];

  const userMenus = [
    {
      key: t('page.management.users'),
      title: t('page.management.users'),
      iconBackground: 'rgb(252, 133, 183, 0.2)',
      icon: (
        <SvgIcon
          icon="icon-park-solid--people"
          size={40}
          style={{
            borderRadius: '12px',
            padding: '3px',
            color: '#fc85b7',
          }}
        />
      ),
      onClick: () => {
        router.push(`/user/manage`);
      },
      desc: t('page.management.usersDesc'),
    },
  ];

  const functionCards = [
    ...(datasetFlag || isAdmin
      ? [
        {
          key: t('page.management.knowledgeManagement'),
          title: t('page.management.knowledgeManagement'),
          iconBackground: '#F6E7FC',
          icon: (
            <SvgIcon
              icon="ri--book-2-fill"
              size={40}
              style={{
                borderRadius: '12px',
                padding: '3px',
                color: '#ce33e6',
              }}
            />
          ),
          onClick: () => {
            // router.pushQuery(`/know`);
            // window.open('/know', '_blank');
            openOrFocusTab('/know', 'knowledgeManagement');
          },
          desc: t('page.management.knowledgeManagementDesc'),
        },
      ]
      : []),
    // ...(apiFlag || isAdmin
    //   ? [
    //       {
    //         key: 'API接口管理',
    //         title: 'API接口管理',
    //         iconBackground: '#E6EFFD',
    //         icon: (
    //           <SvgIcon
    //             icon="icon-park-solid--api"
    //             size={40}
    //             style={{
    //               padding: '4px',
    //               color: '#3783eb',
    //             }}
    //           />
    //         ),
    //         onClick: () => {
    //           router.push(`/datasets/api`);
    //         },
    //         desc: '提供完整的API接口调用管理，简化开发流程，一键集成所需功能',
    //       },
    //     ]
    //   : []),
    ...(datasetFlag || apiFlag || isAdmin
      ? [
        {
          key: t('page.management.rightsManagement'),
          title: t('page.management.rightsManagement'),
          iconBackground: '#E5F5F8',
          icon: (
            <SvgIcon
              icon="fluent-mdl2--permissions-solid"
              size={40}
              style={{
                padding: '6px',
                color: '#29bdb8',
              }}
            />
          ),
          onClick: () => {
            openOrFocusTab('/apps/permission-manage', 'permission-manage');
            // window.open('/apps/permission-manage', '_blank');
            // if (isEnableRoleConditions && isAdmin) {
            //   window.open('/apps/permission-manage', '_blank');
            // } else {
            //   router.push(`/apps/permission`);
            // }
          },
          desc: t('page.management.rightsManagementDesc'),
        },
      ]
      : []),
    ...(isAdmin
      ? [
        {
          key: t('page.management.dataBoard'),
          title: t('page.management.dataBoard'),
          iconBackground: '#F2ECFF',
          icon: (
            <SvgIcon
              icon="icon-park-solid--slide"
              size={40}
              style={{
                padding: '3px',
                color: '#a76cff',
              }}
            />
          ),
          onClick: () => {
            router.push(`/apps/report/${id}`);
          },
          desc: t('page.management.dataBoardDesc'),
        },
        // {
        //   title: t('page.management.applicationManagement'),
        //   iconBackground: '#F8EDEE',
        //   icon: (
        //     <SvgIcon
        //       icon="ri--apps-3-fill"
        //       size={40}
        //       style={{
        //         padding: '3px',
        //         color: '#db9040',
        //       }}
        //     />
        //   ),
        //   onClick: () => {
        //     router.push(`/extension/manage`);
        //   },
        //   desc: t('page.management.applicationManagementDesc'),
        // },
        // {
        //   key: t('page.management.personalization'),
        //   title: t('page.management.personalization'),
        //   classname: 'jr-step-5',
        //   iconBackground: '#F7F0EC',
        //   icon: (
        //     <SvgIcon
        //       icon="ri--apps-2-add-fill"
        //       size={40}
        //       style={{
        //         padding: '3px',
        //         color: '#eb897c',
        //       }}
        //     />
        //   ),
        //   onClick: () => {
        //     router.push(`/extension/manage`);
        //   },
        //   desc: '统一管理各类应用服务',
        // },
        {
          key: t('page.management.personalization'),
          title: t('page.management.personalization'),
          classname: 'jr-step-5',
          iconBackground: '#F8EDEE',
          icon: (
            <SvgIcon
              icon="ri--apps-2-add-fill"
              size={40}
              style={{
                padding: '3px',
                color: '#db9040',
              }}
            />
          ),
          onClick: () => {
            router.push(`/apps/manage/${id}`);
          },
          desc: t('page.management.personalizationDesc'),
        },

        // {
        //   key: t('page.management.rightsManagement'),
        //   title: t('page.management.rightsManagement'),
        //   iconBackground: '#E5F5F8',
        //   icon: (
        //     <SvgIcon
        //       icon="fluent-mdl2--permissions-solid"
        //       size={40}
        //       style={{
        //         padding: '6px',
        //         color: '#29bdb8',
        //       }}
        //     />
        //   ),
        //   onClick: () => {
        //     // router.push(`/apps/permission-manage`);
        //     window.open('/apps/permission-manage', '_blank');
        //   },
        //   desc: t('page.management.rightsManagementDesc'),
        // },
      ]
      : []),
    // ...((isEnableRoleConditions && isAdmin) ? roleMenus : []),
    // ...((isEnableRoleConditions && isAdmin) ? userMenus : []),
    ...(username == 'root' ? [
      {
        key: t('page.management.Singlesignin'),
        title: t('page.management.Singlesignin'),
        iconBackground: '#F8EDEE',
        icon: (
          <SvgIcon
            icon="icon-park-solid--move-in-one"
            size={40}
            style={{
              padding: '3px',
              color: '#db9040',
            }}
          />
        ),
        onClick: () => {
          router.push(`/apps/singleSign/${id}`);
        },
        desc: t('page.management.SinglesigninDesc'),
      }
    ] : [])
  ];

  return (
    <Layout
      className="h-full min-h-screen w-full"
      style={{
        backgroundColor: '#EDF0F8',
      }}
    >
      <div
        onClick={() => {
          setLogoShow(!logoShow);
        }}
      >
        {!isPc && <HeaderLogo />}
      </div>
      <JoyrideGuide />

      <div>
        {isPc ? (
          <HomeMenuList />
        ) : (
          <div style={{ display: logoShow ? 'block' : 'none' }}>{<HomeMenuList />}</div>
        )}
      </div>

      <Content
        className="h-full min-h-screen w-full overflow-auto [-ms-overflow-style:none] [scrollbar-width:none]"
        onClick={() => {
          setLogoShow(false);
        }}
      >
        <div
          className="mx-auto max-w-7xl px-8"
          style={{
            backgroundColor: '#EDF0F8',
          }}
        >
          <div
            className="jr-step-7 mb-6 flex  items-center justify-center"
            style={{ height: isPc ? '218px' : '' }}
          >
            <img src={AppManagerIcon} width={isPc ? '50%' : '100%'} />
          </div>

          <div className="management-sub-title jr-step-8 mb-6 mt-6 flex w-full items-center justify-center">
            {appInfoInitialize?.management_text
              ? appInfoInitialize?.management_text
              : BrandingEnum.management_text}
          </div>

          <div
            className={`grid ${isPc ? 'grid-cols-2 gap-8' : 'grid-cols-1 gap-4'}`}
            style={{
              margin: 'auto',
              width: isPc ? '700px' : '100%',
              paddingBottom: '20px',
            }}
          >
            {functionCards.map((card, index) => (
              <div
                key={index}
                className={`'w-full hover:shadow-md' cursor-pointer rounded-xl bg-white p-4 shadow-sm transition-shadow ${card?.classname
                  } ${licenseFlag && !initializeData?.is_license_valid
                    ? 'cursor-not-allowed opacity-50'
                    : ''
                  }`}
                onClick={
                  licenseFlag && !initializeData?.is_license_valid ? undefined : card.onClick
                }
              >
                <div
                  className="flex w-full items-center space-x-6"
                  style={{ height: isPc ? '72px' : 'unset' }}
                >
                  <div
                    className="bg-purple-50 rounded-xl p-2"
                    style={{
                      backgroundColor: `${card.iconBackground}`,
                      borderRadius: '120px',
                      width: '60px',
                    }}
                  >
                    {card.icon}
                  </div>
                  <div className="w-full min-w-[50px] flex-1">
                    <h3 className="mb-2 text-xl font-medium text-gray-900">
                      {card.title}
                    </h3>
                    <Text
                      ellipsis={!isPc}
                      className="app-desc line-clamp-2 leading-relaxed"
                      style={{
                        width: '100%',
                        color: '#5E6772',
                      }}
                    >
                      {card.desc}
                    </Text>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </Content>
    </Layout>
  );
};

export default memo(App);
